<?php

// 查立得PHP+mysql通用预约排队系统 V2024.12.12
// 演示地址: http://duilie.chalide.cn
// 文件路径: admin.php
// 文件大小: 49097 字节
// 最后修改时间: 2024-12-17 21:00:00
// 作者: yujianyue
// 邮件: 15058593138@qq.com
// 版权所有,保留发行权和署名权
define('IN_SYSTEM', true);
require_once 'inc/conn.php';
require_once 'inc/pubs.php';
require_once 'inc/json.php';

session_start();

// 检查登录状态，未登录跳转到登录页
if(!isset($_SESSION['admin'])) {
    header('Location: login.php');
    exit;
}

// 处理AJAX请求
if(isset($_GET['act'])) {
    switch($_GET['act']) {
        case 'login':
            doLogin();
            break;
        case 'logout':
            doLogout();
            break;
        case 'users':
            getUserList();
            break;
        case 'add_user':
            addUser();
            break;
        case 'edit_user':
            editUser();
            break;
        case 'del_user':
            deleteUser();
            break;
        case 'batch_del':
            batchDelete();
            break;
        case 'stats':
            getStats();
            break;
        case 'download_stats':
            downloadStats();
            break;
        case 'bookings':
            getBookings();
            break;
        case 'download_bookings':
            downloadBookings();
            break;
        case 'settings':
            saveSettings();
            break;
        case 'password':
            changePassword();
            break;
        default:
            json_msg(0, '未知操作');
    }
    exit;
}

// 退出登录
function doLogout() {
    unset($_SESSION['admin']);
    header('Location: login.php');
    exit;
}

// 获取用户列表
function getUserList() {
    global $conn;
    checkLogin();
    
    $page = isset($_GET['page']) ? intval($_GET['page']) : 1;
    $limit = 10;
    $offset = ($page - 1) * $limit;
    
    $field = isset($_GET['field']) ? safe_string($_GET['field']) : '';
    $keyword = isset($_GET['keyword']) ? safe_string($_GET['keyword']) : '';
    
    $where = "1=1";
    if($field && $keyword) {
        $where .= " AND $field LIKE '%$keyword%'";
    }
    
    // 获取总数
    $sql = "SELECT COUNT(*) as total FROM doctor WHERE $where";
    $total = $conn->query($sql)->fetch_assoc()['total'];
    
    // 获取当页数据
    $sql = "SELECT * FROM doctor 
            WHERE $where 
            ORDER BY id DESC 
            LIMIT $offset, $limit";
    $result = $conn->query($sql);
    
    $list = array();
    while($row = $result->fetch_assoc()) {
        $list[] = array(
            'id' => $row['id'],
            'username' => $row['username'],
            'name' => $row['name'],
            'department' => $row['department'],
            'status' => $row['status'],
            'last_login' => $row['last_login']
        );
    }
    
    json_msg(1, 'success', array(
        'list' => $list,
        'total' => $total,
        'page' => $page,
        'pages' => ceil($total / $limit)
    ));
}

// 添加用户
function addUser() {
    global $conn;
    checkLogin();
    
    $username = isset($_POST['username']) ? safe_string($_POST['username']) : '';
    $password = isset($_POST['password']) ? safe_string($_POST['password']) : '';
    $name = isset($_POST['name']) ? safe_string($_POST['name']) : '';
    $department = isset($_POST['department']) ? safe_string($_POST['department']) : '';
    
    if(empty($username) || empty($password) || empty($name) || empty($department)) {
        json_msg(0, '请填写完整信息');
    }
    
    // 检查用户名是否存在
    $sql = "SELECT id FROM doctor WHERE username = '$username'";
    if($conn->query($sql)->fetch_assoc()) {
        json_msg(0, '用户名已存在');
    }
    
    $password = md5($password);
    $sql = "INSERT INTO doctor (username, password, name, department) 
            VALUES ('$username', '$password', '$name', '$department')";
            
    if($conn->query($sql)) {
        json_msg(1, '添加成功');
    } else {
        json_msg(0, '添加失败');
    }
}

// 编辑用户
function editUser() {
    global $conn;
    checkLogin();
    
    $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
    $name = isset($_POST['name']) ? safe_string($_POST['name']) : '';
    $department = isset($_POST['department']) ? safe_string($_POST['department']) : '';
    $password = isset($_POST['password']) ? safe_string($_POST['password']) : '';
    
    if(!$id || empty($name) || empty($department)) {
        json_msg(0, '参数错误');
    }
    
    $sql = "UPDATE doctor SET 
            name = '$name', 
            department = '$department'";
            
    if($password) {
        $password = md5($password);
        $sql .= ", password = '$password'";
    }
    
    $sql .= " WHERE id = $id";
    
    if($conn->query($sql)) {
        json_msg(1, '修改成功');
    } else {
        json_msg(0, '修改失败');
    }
}

// 删除用户
function deleteUser() {
    global $conn;
    checkLogin();
    
    $id = isset($_POST['id']) ? intval($_POST['id']) : 0;
    
    if(!$id) {
        json_msg(0, '参数错误');
    }
    
    $sql = "DELETE FROM doctor WHERE id = $id";
    if($conn->query($sql)) {
        json_msg(1, '删除成功');
    } else {
        json_msg(0, '删除失败');
    }
}

// 批量删除
function batchDelete() {
    global $conn;
    checkLogin();
    
    $ids = isset($_POST['ids']) ? $_POST['ids'] : '';
    
    if(empty($ids)) {
        json_msg(0, '请选择要删除的记录');
    }
    
    // 提取数字ID
    preg_match_all('/\d+/', $ids, $matches);
    $ids = implode(',', $matches[0]);
    
    if(empty($ids)) {
        json_msg(0, '参数错误');
    }
    
    $sql = "DELETE FROM doctor WHERE id IN ($ids)";
    if($conn->query($sql)) {
        json_msg(1, '删除成功');
    } else {
        json_msg(0, '删除失败');
    }
}

// 获取统计信息
function getStats() {
    global $conn;
    checkLogin();
    
    $doctor_id = isset($_GET['doctor_id']) ? intval($_GET['doctor_id']) : 0;
    
    // 获取医生列表
    $sql = "SELECT id, name, department FROM doctor ORDER BY id DESC";
    $result = $conn->query($sql);
    $doctors = array();
    while($row = $result->fetch_assoc()) {
        $doctors[] = $row;
    }
    
    if($doctor_id) {
        // 获取指定医生统计
        $sql = "SELECT 
                booking_date,
                SUM(status = 0) as waiting,
                SUM(status = 1) as verified
                FROM booking 
                WHERE doctor_id = $doctor_id
                GROUP BY booking_date 
                ORDER BY booking_date DESC";
        $result = $conn->query($sql);
        $stats = array();
        while($row = $result->fetch_assoc()) {
            $stats[] = $row;
        }
    } else {
        $stats = array();
    }
    
    json_msg(1, 'success', array(
        'doctors' => $doctors,
        'stats' => $stats
    ));
}

// 下载统计
function downloadStats() {
    global $conn;
    checkLogin();
    
    $doctor_id = isset($_GET['doctor_id']) ? intval($_GET['doctor_id']) : 0;
    if(!$doctor_id) {
        die('参数错误');
    }
    
    // 获取医生信息
    $sql = "SELECT name, department FROM doctor WHERE id = $doctor_id";
    $doctor = $conn->query($sql)->fetch_assoc();
    
    // 获取统计数据
    $sql = "SELECT 
            booking_date,
            SUM(status = 0) as waiting,
            SUM(status = 1) as verified
            FROM booking 
            WHERE doctor_id = $doctor_id
            GROUP BY booking_date 
            ORDER BY booking_date DESC";
    $result = $conn->query($sql);
    
    $filename = "统计报告_{$doctor['name']}_{$doctor['department']}_" . date('YmdHis') . ".txt";
    
    header('Content-Type: text/plain');
    header('Content-Disposition: attachment; filename=' . $filename);
    
    echo "医生：{$doctor['name']}\n";
    echo "科室：{$doctor['department']}\n";
    echo "统计时间：" . date('Y-m-d H:i:s') . "\n\n";
    echo "日期\t待核销\t已核销\n";
    
    while($row = $result->fetch_assoc()) {
        echo "{$row['booking_date']}\t{$row['waiting']}\t{$row['verified']}\n";
    }
    
    exit;
}

// 获取预约记录
function getBookings() {
    global $conn;
    checkLogin();
    
    $page = isset($_GET['page']) ? intval($_GET['page']) : 1;
    $limit = 10;
    $offset = ($page - 1) * $limit;
    
    $field = isset($_GET['field']) ? safe_string($_GET['field']) : '';
    $keyword = isset($_GET['keyword']) ? safe_string($_GET['keyword']) : '';
    
    $where = "1=1";
    if($field && $keyword) {
        $where .= " AND $field LIKE '%$keyword%'";
    }
    
    // 获取总数
    $sql = "SELECT COUNT(*) as total FROM booking WHERE $where";
    $total = $conn->query($sql)->fetch_assoc()['total'];
    
    // 获取当页数据
    $sql = "SELECT * FROM booking 
            WHERE $where 
            ORDER BY id DESC 
            LIMIT $offset, $limit";
    $result = $conn->query($sql);
    
    $list = array();
    while($row = $result->fetch_assoc()) {
        $list[] = array(
            'sequence' => $row['sequence'],
            'department' => $row['department'],
            'doctor_name' => $row['doctor_name'],
            'patient_name' => $row['patient_name'],
            'mobile' => substr_replace($row['mobile'], '****', 3, 4),
            'booking_date' => $row['booking_date'],
            'booking_time' => $row['booking_time'],
            'status' => $row['status'],
            'verify_time' => $row['verify_time']
        );
    }
    
    json_msg(1, 'success', array(
        'list' => $list,
        'total' => $total,
        'page' => $page,
        'pages' => ceil($total / $limit)
    ));
}

// 下载预约记录
function downloadBookings() {
    global $conn;
    checkLogin();
    
    $field = isset($_GET['field']) ? safe_string($_GET['field']) : '';
    $keyword = isset($_GET['keyword']) ? safe_string($_GET['keyword']) : '';
    
    $where = "1=1";
    if($field && $keyword) {
        $where .= " AND $field LIKE '%$keyword%'";
    }
    
    $sql = "SELECT * FROM booking 
            WHERE $where 
            ORDER BY id DESC";
    $result = $conn->query($sql);
    
    $filename = "预约记录_" . date('YmdHis') . ".txt";
    
    header('Content-Type: text/plain');
    header('Content-Disposition: attachment; filename=' . $filename);
    
    echo "序号\t科室\t医生\t姓名\t手机号\t预约日期\t预约时间\t状态\t核销时间\n";
    
    while($row = $result->fetch_assoc()) {
        echo "{$row['sequence']}\t{$row['department']}\t{$row['doctor_name']}\t" .
             "{$row['patient_name']}\t{$row['mobile']}\t{$row['booking_date']}\t" .
             "{$row['booking_time']}\t" . 
             ($row['status'] ? '已核销' : '未核销') . "\t" .
             ($row['verify_time'] ?: '') . "\n";
    }
    
    exit;
}

// 保存设置
function saveSettings() {
    global $conn, $CONFIG;
    checkLogin();
    
    $settings = isset($_POST['settings']) ? $_POST['settings'] : array();
    
    if(empty($settings)) {
        json_msg(0, '参数错误');
    }
    
    // 更新配置
    foreach($settings as $key => $value) {
        if(isset($CONFIG[$key])) {
            $CONFIG[$key] = $value;
        }
    }
    
    // 保存到文件
    if(!file_exists(__DIR__ . '/inc/cache/')) {
        mkdir(__DIR__ . '/inc/cache/', 0777, true);
    }
    
    if(file_put_contents(__DIR__ . '/inc/cache/config.json', 
        json_encode($CONFIG, JSON_UNESCAPED_UNICODE))) {
        json_msg(1, '设置已保存');
    } else {
        json_msg(0, '保存失败');
    }
}

// 修改密码
function changePassword() {
    global $conn;
    checkLogin();
    
    $old_pwd = isset($_POST['old_pwd']) ? safe_string($_POST['old_pwd']) : '';
    $new_pwd = isset($_POST['new_pwd']) ? safe_string($_POST['new_pwd']) : '';
    $confirm_pwd = isset($_POST['confirm_pwd']) ? safe_string($_POST['confirm_pwd']) : '';
    
    if(empty($old_pwd) || empty($new_pwd) || empty($confirm_pwd)) {
        json_msg(0, '请填写完整');
    }
    
    if(!preg_match('/^[a-zA-Z0-9]{6,16}$/', $new_pwd)) {
        json_msg(0, '新密码必须为6-16位数字字母');
    }
    
    if($new_pwd !== $confirm_pwd) {
        json_msg(0, '两次输入的新密码不一致');
    }
    
    // 验证旧密码
    $old_pwd = md5($old_pwd);
    $admin = $_SESSION['admin'];
    $sql = "SELECT id FROM admin 
            WHERE id = {$admin['id']} 
            AND password = '$old_pwd'";
    if(!$conn->query($sql)->fetch_assoc()) {
        json_msg(0, '旧密码错误');
    }
    
    // 更新密码
    $new_pwd = md5($new_pwd);
    $sql = "UPDATE admin 
            SET password = '$new_pwd' 
            WHERE id = {$admin['id']}";
            
    if($conn->query($sql)) {
        json_msg(1, '密码修改成功，请重新登录');
    } else {
        json_msg(0, '修改失败，请重试');
    }
}

// 检查登录状态
function checkLogin() {
    if(!isset($_SESSION['admin'])) {
        json_msg(0, '请先登录');
    }
}

?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>系统管理 - <?php echo $CONFIG['site_title']; ?></title>
    <script>
        // 将PHP配置传递给JavaScript
        var CONFIG = <?php echo json_encode($CONFIG); ?>;
    </script>
    <style>
        body { 
            font-family: Arial; 
            max-width: 1200px; 
            margin: 0 auto; 
            padding: 20px;
        }
        
        /* 登录表单样式 */
        .login-form {
            max-width: 400px;
            margin: 100px auto;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 4px;
            text-align: center;
        }
        .login-form h2 {
            margin-bottom: 20px;
        }
        
        /* 表单项通用样式 */
        .form-item {
            margin: 15px 0;
        }
        .form-item input, .form-item select {
            width: 100%;
            padding: 8px;
            box-sizing: border-box;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .form-item label {
            display: block;
            margin-bottom: 5px;
            color: #666;
        }
        
        /* 按钮样式 */
        .btn, .mask-buttons button {
            padding: 8px;
            background: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .btn:hover {
            background: #0056b3;
        }
        .btn-danger {
            background: #dc3545;
        }
        .btn-danger:hover {
            background: #c82333;
        }
        .btn-logout {
            padding: 5px 8px;
            background: #dc3545;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        
        /* 头部样式 */
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        .header h1 {
            margin: 0;
        }
        
        /* 标签页样式 */
        .tabs {
            display: flex;
            border-bottom: 1px solid #ddd;
            margin-bottom: 20px;
        }
        .tab {
            padding: 10px 20px;
            cursor: pointer;
            border: 1px solid transparent;
            margin-bottom: -1px;
        }
        .tab:hover {
            background: #f8f9fa;
        }
        .tab.active {
            border: 1px solid #ddd;
            border-bottom-color: white;
            background: white;
        }
        
        /* 内容区域样式 */
        #tab-content {
            min-height: 400px;
            padding: 20px 0;
        }
        
        /* 表格样式 */
        .table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }
        .table th, .table td {
            padding: 5px;
            border: 1px solid #ddd;
            text-align: left;
        }
        .table th {
            background: #f8f9fa;
        }
        .table tr:hover {
            background: #f8f9fa;
        }
        
        /* 工具栏样式 */
        .toolbar {
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            flex-wrap: wrap;
            gap: 10px;
        }
        .toolbar select {
            padding: 6px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .toolbar input {
            padding: 6px;
            border: 1px solid #ddd;
            border-radius: 4px;
            width: 200px;
        }
        
        /* 分页样式 */
        .pagination {
            margin-top: 20px;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .pagination select {
            margin: 0 10px;
            padding: 5px;
        }
        .pagination button {
            padding: 5px 10px;
            margin: 0 5px;
            border: 1px solid #ddd;
            background: white;
            cursor: pointer;
            border-radius: 4px;
        }
        .pagination button:hover {
            background: #f8f9fa;
        }
        .pagination button:disabled {
            background: #f8f9fa;
            cursor: not-allowed;
        }
        
        /* 统计信息样式 */
        .stats-box {
            margin-bottom: 30px;
        }
        .stats-box select {
            padding: 8px;
            margin-right: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .stats-summary {
            display: flex;
            justify-content: space-around;
            margin: 20px 0;
            text-align: center;
        }
        .stats-summary .number {
            font-size: 36px;
            font-weight: bold;
            color: #007bff;
        }
        .stats-summary .label {
            color: #666;
        }
        
        /* 设置表单样式 */
        .setting-form {
            max-width: 600px;
        }
        .setting-form .form-item {
            margin-bottom: 20px;
        }
        .setting-form textarea {
            width: 100%;
            height: 100px;
            padding: 8px;
            box-sizing: border-box;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        
        /* 遮罩层样式 */
        .mask {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }
        .mask-box {
            background: white;
            padding: 20px;
            border-radius: 4px;
            min-width: 300px;
            max-width: 90%;
            max-height: 90vh;
            overflow-y: auto;
            position: relative;
        }
        .mask-close {
            position: absolute;
            right: 10px;
            top: 10px;
            cursor: pointer;
            font-size: 20px;
            color: #666;
        }
        .mask-title {
            margin: 0 0 20px 0;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
        }
        .mask-content {
            margin-bottom: 20px;
        }
        .mask-buttons {
            text-align: right;
            padding-top: 15px;
            border-top: 1px solid #eee;
        }
        
        /* 复选框样式 */
        .checkbox-wrap {
            display: inline-block;
            margin-right: 10px;
        }
        .checkbox-wrap input[type="checkbox"] {
            margin-right: 5px;
        }
        
        /* 响应式布局 */
        @media (max-width: 768px) {
            .toolbar {
                flex-direction: column;
                align-items: stretch;
            }
            .toolbar input {
                width: 100%;
            }
            .table {
                display: block;
                overflow-x: auto;
            }
            .stats-summary {
                flex-direction: column;
                gap: 20px;
            }
        }
    </style>
</head>
<body>
    <div id="main">
        <div class="header">
            <h1>系统管理</h1>
            <button class="btn-logout" onclick="doLogout()">退出</button>
        </div>
        
        <div class="tabs">
            <div class="tab active" onclick="switchTab(0)">用户列表</div>
            <div class="tab" onclick="switchTab(1)">统计信息</div>
            <div class="tab" onclick="switchTab(2)">预约记录</div>
            <div class="tab" onclick="switchTab(3)">系统设置</div>
            <div class="tab" onclick="switchTab(4)">修改密码</div>
        </div>
        
        <div id="tab-content">
            <!-- 内容将由JavaScript动态加载 -->
        </div>
    </div>

    <script src="inc/js.js"></script>
    <script>
        // 全局变量
        var currentTab = 0;
        var currentPage = 1;
        var searchField = '';
        var searchKeyword = '';

        // 页面加载完成检查登录状态
        window.onload = function() {
            checkLoginStatus();
        };

        // 检查登录状态
        function checkLoginStatus() {
            // 由于已经在PHP中检查了登录状态，这里只需要加载默认标签页
            loadTabContent(0);
        }

        // 登录
        function doLogin() {
            var username = document.getElementById('username').value;
            var password = document.getElementById('password').value;
            
            ajax({
                url: '?act=login',
                type: 'POST',
                data: {
                    act: 'login',
                    username: username,
                    password: password
                },
                success: function(res) {
                    var data = JSON.parse(res);
                    if(data.code === 1) {
                        checkLoginStatus();
                    } else {
                        alert(data.msg);
                    }
                }
            });
        }

        // 退出登录
        function doLogout() {
            window.location.href = 'admin.php?act=logout';
        }

        // 切换标签页
        function switchTab(index) {
            var tabs = document.getElementsByClassName('tab');
            for(var i = 0; i < tabs.length; i++) {
                tabs[i].className = 'tab' + (i === index ? ' active' : '');
            }
            currentTab = index;
            loadTabContent(index);
        }

        // 加载标签页内容
        function loadTabContent(index) {
            switch(index) {
                case 0: // 用户列表
                    loadUserList();
                    break;
                case 1: // 统计信息
                    loadStats();
                    break;
                case 2: // 预约记录
                    loadBookings();
                    break;
                case 3: // 系统设置
                    loadSettings();
                    break;
                case 4: // 修改密码
                    loadPasswordForm();
                    break;
            }
        }

        // 加载用户列表
        function loadUserList(page) {
            currentPage = page || currentPage;
            
            var html = '<div class="toolbar">' +
                       '<select id="field">' +
                       '<option value="username">用户名</option>' +
                       '<option value="name">姓名</option>' +
                       '<option value="department">科室</option>' +
                       '</select>' +
                       '<input type="text" id="keyword" placeholder="搜索关键词" value="' + searchKeyword + '">' +
                       '<button class="btn" onclick="searchUsers()">搜索</button>' +
                       '<button class="btn" onclick="showAddUser()">添加用户</button>' +
                       '<button class="btn btn-danger" onclick="batchDelete()">批量删除</button>' +
                       '</div>';
                       
            ajax({
                url: 'admin.php',
                type: 'GET',
                data: {
                    act: 'users',
                    page: currentPage,
                    field: searchField,
                    keyword: searchKeyword
                },
                success: function(res) {
                    var data = JSON.parse(res);
                    if(data.code === 1) {
                        html += '<table class="table">' +
                               '<tr>' +
                               '<th><input type="checkbox" onclick="toggleAll(this)"></th>' +
                               '<th>用户名</th>' +
                               '<th>姓名</th>' +
                               '<th>科室</th>' +
                               '<th>状态</th>' +
                               '<th>最后登录</th>' +
                               '<th>操作</th>' +
                               '</tr>';
                                
                        data.data.list.forEach(function(item) {
                            html += '<tr>' +
                                   '<td><input type="checkbox" value="' + item.id + '"></td>' +
                                   '<td>' + item.username + '</td>' +
                                   '<td>' + item.name + '</td>' +
                                   '<td>' + item.department + '</td>' +
                                   '<td>' + (item.status == 1 ? '开启' : '关闭') + '</td>' +
                                   '<td>' + (item.last_login || '-') + '</td>' +
                                   '<td>' +
                                   '<button class="btn" onclick="showEditUser(' + item.id + 
                                   ',\'' + item.name + '\',\'' + item.department + '\')">修改</button> ' +
                                   '<button class="btn btn-danger" onclick="deleteUser(' + item.id + 
                                   ')">删除</button>' +
                                   '</td>' +
                                   '</tr>';
                        });
                                
                        html += '</table>';
                                
                        // 添加分页
                        if(data.data.total > 0) {
                            html += createPagination(data.data.page, data.data.pages);
                        }
                                
                        document.getElementById('tab-content').innerHTML = html;
                                
                        // 恢复搜索条件
                        if(searchField) {
                            document.getElementById('field').value = searchField;
                        }
                    }
                }
            });
        }

        // 搜索用户
        function searchUsers() {
            searchField = document.getElementById('field').value;
            searchKeyword = document.getElementById('keyword').value;
            loadUserList(1);
        }

        // 显示添加用户表单
        function showAddUser() {
            var content = '<div class="form-item">' +
                          '<label>用户名</label>' +
                          '<input type="text" id="add_username">' +
                          '</div>' +
                          '<div class="form-item">' +
                          '<label>密码</label>' +
                          '<input type="password" id="add_password">' +
                          '</div>' +
                          '<div class="form-item">' +
                          '<label>姓名</label>' +
                          '<input type="text" id="add_name">' +
                          '</div>' +
                          '<div class="form-item">' +
                          '<label>科室</label>' +
                          '<input type="text" id="add_department">' +
                          '</div>';
                          
            showMask(content, [{
                text: '确定',
                click: function() {
                    addUser();
                }
            }]);
        }

        // 添加用户
        function addUser() {
            var username = document.getElementById('add_username').value;
            var password = document.getElementById('add_password').value;
            var name = document.getElementById('add_name').value;
            var department = document.getElementById('add_department').value;
            
            ajax({
                url: '?act=add_user',
                type: 'POST',
                data: {
                    act: 'add_user',
                    username: username,
                    password: password,
                    name: name,
                    department: department
                },
                success: function(res) {
                    var data = JSON.parse(res);
                    alert(data.msg);
                    if(data.code === 1) {
                        document.body.removeChild(document.querySelector('.mask'));
                        loadUserList();
                    }
                }
            });
        }

        // 显示编辑用户表单
        function showEditUser(id, name, department) {
            var content = '<div class="form-item">' +
                          '<label>姓名</label>' +
                          '<input type="text" id="edit_name" value="' + name + '">' +
                          '</div>' +
                          '<div class="form-item">' +
                          '<label>科室</label>' +
                          '<input type="text" id="edit_department" value="' + department + '">' +
                          '</div>' +
                          '<div class="form-item">' +
                          '<label>新密码(不修改请留空)</label>' +
                          '<input type="password" id="edit_password">' +
                          '</div>';
                          
            showMask(content, [{
                text: '确定',
                click: function() {
                    editUser(id);
                }
            }]);
        }

        // 编辑用户
        function editUser(id) {
            var name = document.getElementById('edit_name').value;
            var department = document.getElementById('edit_department').value;
            var password = document.getElementById('edit_password').value;
            
            ajax({
                url: '?act=edit_user',
                type: 'POST',
                data: {
                    act: 'edit_user',
                    id: id,
                    name: name,
                    department: department,
                    password: password
                },
                success: function(res) {
                    var data = JSON.parse(res);
                    alert(data.msg);
                    if(data.code === 1) {
                        document.body.removeChild(document.querySelector('.mask'));
                        loadUserList();
                    }
                }
            });
        }

        // 删除用户
        function deleteUser(id) {
            if(!confirm('确定要删除此用户吗？')) {
                return;
            }
            
            ajax({
                url: '?act=del_user',
                type: 'POST',
                data: {
                    act: 'del_user',
                    id: id
                },
                success: function(res) {
                    var data = JSON.parse(res);
                    alert(data.msg);
                    if(data.code === 1) {
                        loadUserList();
                    }
                }
            });
        }

        // 批量删除
        function batchDelete() {
            var checkboxes = document.querySelectorAll('input[type="checkbox"]:checked');
            var ids = [];
            
            checkboxes.forEach(function(checkbox) {
                if(checkbox.value) {
                    ids.push(checkbox.value);
                }
            });
            
            if(ids.length === 0) {
                alert('请选择要删除的记录');
                return;
            }
            
            if(!confirm('确定要删除选中的记录吗？')) {
                return;
            }
            
            ajax({
                url: '?act=batch_del',
                type: 'POST',
                data: {
                    act: 'batch_del',
                    ids: ids.join(',')
                },
                success: function(res) {
                    var data = JSON.parse(res);
                    alert(data.msg);
                    if(data.code === 1) {
                        loadUserList();
                    }
                }
            });
        }

        // 全选/取消全选
        function toggleAll(checkbox) {
            var checkboxes = document.querySelectorAll('input[type="checkbox"]');
            checkboxes.forEach(function(item) {
                item.checked = checkbox.checked;
            });
        }

        // 加载统计信息
        function loadStats() {
            var html = '<div class="stats-box">' +
                       '<select id="doctor_id" onchange="changeDoctorStats(this.value)">' +
                       '<option value="">请选择医生</option>' +
                       '</select>' +
                       '<button class="btn" onclick="downloadStats()">下载报告</button>' +
                       '</div>' +
                       '<div id="stats-content"></div>';
                       
            document.getElementById('tab-content').innerHTML = html;
            
            // 加载医生列表
            ajax({
                url: 'admin.php',
                type: 'GET',
                data: {act: 'stats'},
                success: function(res) {
                    var data = JSON.parse(res);
                    if(data.code === 1) {
                        var select = document.getElementById('doctor_id');
                        data.data.doctors.forEach(function(doctor) {
                            var option = document.createElement('option');
                            option.value = doctor.id;
                            option.textContent = doctor.name + ' - ' + doctor.department;
                            select.appendChild(option);
                        });
                    }
                }
            });
        }

        // 切换医生统计
        function changeDoctorStats(doctor_id) {
            if(!doctor_id) {
                document.getElementById('stats-content').innerHTML = '';
                return;
            }
            
            ajax({
                url: 'admin.php',
                type: 'GET',
                data: {
                    act: 'stats',
                    doctor_id: doctor_id
                },
                success: function(res) {
                    var data = JSON.parse(res);
                    if(data.code === 1) {
                        var html = '<table class="table">' +
                                  '<tr><th>日期</th><th>待核销</th><th>已核销</th></tr>';
                                  
                        data.data.stats.forEach(function(item) {
                            html += '<tr>' +
                                   '<td>' + item.booking_date + '</td>' +
                                   '<td>' + item.waiting + '</td>' +
                                   '<td>' + item.verified + '</td>' +
                                   '</tr>';
                        });
                                  
                        html += '</table>';
                        document.getElementById('stats-content').innerHTML = html;
                    }
                }
            });
        }

        // 下载统计报告
        function downloadStats() {
            var doctor_id = document.getElementById('doctor_id').value;
            if(!doctor_id) {
                alert('请选择医生');
                return;
            }
            
            window.location.href = 'admin.php?act=download_stats&doctor_id=' + doctor_id;
        }

        // 加载预约记录
        function loadBookings(page) {
            currentPage = page || currentPage;
            
            var html = '<div class="toolbar">' +
                       '<select id="field">' +
                       '<option value="sequence">序号</option>' +
                       '<option value="department">科室</option>' +
                       '<option value="doctor_name">医生</option>' +
                       '<option value="patient_name">患者</option>' +
                       '<option value="mobile">手机号</option>' +
                       '</select>' +
                       '<input type="text" id="keyword" placeholder="搜索关键词" value="' + searchKeyword + '">' +
                       '<button class="btn" onclick="searchBookings()">搜索</button>' +
                       '<button class="btn" onclick="downloadBookings()">下载记录</button>' +
                       '</div>';
                       
            ajax({
                url: 'admin.php',
                type: 'GET',
                data: {
                    act: 'bookings',
                    page: currentPage,
                    field: searchField,
                    keyword: searchKeyword
                },
                success: function(res) {
                    var data = JSON.parse(res);
                    if(data.code === 1) {
                        html += '<table class="table">' +
                               '<tr>' +
                               '<th>序号</th>' +
                               '<th>科室</th>' +
                               '<th>医生</th>' +
                               '<th>患者</th>' +
                               '<th>手机号</th>' +
                               '<th>预约日期</th>' +
                               '<th>预约时间</th>' +
                               '<th>状态</th>' +
                               '<th>核销时间</th>' +
                               '</tr>';
                                
                        data.data.list.forEach(function(item) {
                            html += '<tr>' +
                                   '<td>' + item.sequence + '</td>' +
                                   '<td>' + item.department + '</td>' +
                                   '<td>' + item.doctor_name + '</td>' +
                                   '<td>' + item.patient_name + '</td>' +
                                   '<td>' + item.mobile + '</td>' +
                                   '<td>' + item.booking_date + '</td>' +
                                   '<td>' + item.booking_time + '</td>' +
                                   '<td>' + (item.status == 1 ? '已核销' : '未核销') + '</td>' +
                                   '<td>' + (item.verify_time || '-') + '</td>' +
                                   '</tr>';
                        });
                                
                        html += '</table>';
                                
                        // 添加分页
                        if(data.data.total > 0) {
                            html += createPagination(data.data.page, data.data.pages);
                        }
                                
                        document.getElementById('tab-content').innerHTML = html;
                                
                        // 恢复搜索条件
                        if(searchField) {
                            document.getElementById('field').value = searchField;
                        }
                    }
                }
            });
        }

        // 搜索预约记录
        function searchBookings() {
            searchField = document.getElementById('field').value;
            searchKeyword = document.getElementById('keyword').value;
            loadBookings(1);
        }

        // 下载预约记录
        function downloadBookings() {
            window.location.href = 'admin.php?act=download_bookings&field=' + searchField + 
                                  '&keyword=' + searchKeyword;
        }

        // 加载系统设置
        function loadSettings() {
            var html = '<div class="setting-form">' +
                       '<div class="form-item">' +
                       '<label>单位名称</label>' +
                       '<input type="text" id="site_name" value="' + CONFIG.site_name + '">' +
                       '</div>' +
                       '<div class="form-item">' +
                       '<label>页面标题</label>' +
                       '<input type="text" id="site_title" value="' + CONFIG.site_title + '">' +
                       '</div>' +
                       '<div class="form-item">' +
                       '<label>二维码刷新频率(秒)</label>' +
                       '<input type="number" id="qrcode_refresh" value="' + CONFIG.qrcode_refresh + '">' +
                       '</div>' +
                       '<div class="form-item">' +
                       '<label>二维码有效期(秒)</label>' +
                       '<input type="number" id="qrcode_expire" value="' + CONFIG.qrcode_expire + '">' +
                       '</div>' +
                       '<div class="form-item">' +
                       '<label>提交有效期(秒)</label>' +
                       '<input type="number" id="submit_expire" value="' + CONFIG.submit_expire + '">' +
                       '</div>' +
                       '<div class="form-item">' +
                       '<label>身份证是否必填</label>' +
                       '<select id="id_card_required">' +
                       '<option value="1"' + (CONFIG.id_card_required ? ' selected' : '') + '>是</option>' +
                       '<option value="0"' + (!CONFIG.id_card_required ? ' selected' : '') + '>否</option>' +
                       '</select>' +
                       '</div>' +
                       '<div class="form-item">' +
                       '<label>预约规则</label>' +
                       '<textarea id="booking_rules">' + CONFIG.booking_rules + '</textarea>' +
                       '</div>' +
                       '<div class="form-item">' +
                       '<label>使用帮助</label>' +
                       '<textarea id="help_content">' + CONFIG.help_content + '</textarea>' +
                       '</div>' +
                       '<button class="btn" onclick="saveSettings()">保存设置</button>' +
                       '</div>';
                       
            document.getElementById('tab-content').innerHTML = html;
        }

        // 保存系统设置
        function saveSettings() {
            var settings = {
                site_name: document.getElementById('site_name').value,
                site_title: document.getElementById('site_title').value,
                qrcode_refresh: document.getElementById('qrcode_refresh').value,
                qrcode_expire: document.getElementById('qrcode_expire').value,
                submit_expire: document.getElementById('submit_expire').value,
                id_card_required: document.getElementById('id_card_required').value == '1',
                booking_rules: document.getElementById('booking_rules').value,
                help_content: document.getElementById('help_content').value
            };
            
            ajax({
                url: '?act=settings',
                type: 'POST',
                data: {
                    act: 'settings',
                    settings: settings
                },
                success: function(res) {
                    var data = JSON.parse(res);
                    alert(data.msg);
                }
            });
        }

        // 加载修改密码表单
        function loadPasswordForm() {
            var html = '<div class="setting-form">' +
                       '<div class="form-item">' +
                       '<label>旧密码</label>' +
                       '<input type="password" id="old_pwd">' +
                       '</div>' +
                       '<div class="form-item">' +
                       '<label>新密码</label>' +
                       '<input type="password" id="new_pwd">' +
                       '</div>' +
                       '<div class="form-item">' +
                       '<label>确认新密码</label>' +
                       '<input type="password" id="confirm_pwd">' +
                       '</div>' +
                       '<button class="btn" onclick="changePassword()">修改</button>' +
                       '</div>';
                       
            document.getElementById('tab-content').innerHTML = html;
        }

        // 修改密码
        function changePassword() {
            var old_pwd = document.getElementById('old_pwd').value;
            var new_pwd = document.getElementById('new_pwd').value;
            var confirm_pwd = document.getElementById('confirm_pwd').value;
            
            ajax({
                url: '?act=password',
                type: 'POST',
                data: {
                    act: 'password',
                    old_pwd: old_pwd,
                    new_pwd: new_pwd,
                    confirm_pwd: confirm_pwd
                },
                success: function(res) {
                    var data = JSON.parse(res);
                    alert(data.msg);
                    if(data.code === 1) {
                        location.reload();
                    }
                }
            });
        }

        // 创建分页HTML
        function createPagination(current, total) {
            var html = '<div class="pagination">';
            
            // 首页
            html += '<button ' + (current == 1 ? 'disabled' : '') + 
                    ' onclick="loadUserList(1)">首页</button>';
            
            // 上一页
            html += '<button ' + (current == 1 ? 'disabled' : '') + 
                    ' onclick="loadUserList(' + (current - 1) + ')">上一页</button>';
            
            // 页码选择
            html += '<select onchange="loadUserList(this.value)">';
            for(var i = 1; i <= total; i++) {
                html += '<option value="' + i + '"' + (i == current ? ' selected' : '') + 
                        '>第' + i + '页</option>';
            }
            html += '</select>';
            
            // 下一页
            html += '<button ' + (current == total ? 'disabled' : '') + 
                    ' onclick="loadUserList(' + (current + 1) + ')">下一页</button>';
            
            // 末页
            html += '<button ' + (current == total ? 'disabled' : '') + 
                    ' onclick="loadUserList(' + total + ')">末页</button>';
                    
            html += '</div>';
            return html;
        }
    </script>
</body>
</html> 